package com.wolfking.back.core.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.wolfking.back.core.exception.SignException;

/**
 * 异常的控制类
 * <P>
 * SignExcption登录异常
 * <P>
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月19日下午4:48:57
 * @版权 归wolfking所有
 */
@Component
@EnableConfigurationProperties(SsoConfig.class)
public class ExceptionHandler implements HandlerExceptionResolver {

	@Autowired
	private SsoConfig ssoConfig;

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		if (ex instanceof SignException) {
			if (StringUtils.isEmpty(SignException.class.cast(ex).getPermission())) {
				String loginFromUrl = ssoConfig.getLoginUrl();
				String requestUrl = request.getRequestURL().toString();
				if (StringUtils.isNotBlank(request.getQueryString()))
					requestUrl = requestUrl + "?" + request.getQueryString();
				requestUrl = "from=" + requestUrl;
				loginFromUrl += ssoConfig.getLoginUrl().contains("?") ? "&" : "?";
				loginFromUrl += requestUrl;
				return new ModelAndView("redirect:" + loginFromUrl);
			} else {
				ModelAndView model = new ModelAndView("redirect:" + ssoConfig.getPermissionUrl());
				model.addObject("message", SignException.class.cast(ex).getPermission());
				model.addObject("detail", "用户权限不足，请联系管理员");
				return model;
			}
		}
		return null;
	}

}
